﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ControllerClient
{
    class SerialPortComImplement
    {
        public delegate void RecEventHandler(byte[] queueByte);
        public event RecEventHandler DataReceivedEvent;
        private SerialPort serialPort;
        private List<byte> buffer = new List<byte>(4096);
        private  int LOCK_WHAT = 2;
        private  int LOCK_LOG_WHAT = 3;
        PSAMHelper PSAMHelper = null;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="portName">端口名称</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="dataBits">数据位</param>
        public SerialPortComImplement(string portName, int baudRate, int dataBits)
        {
            serialPort = new SerialPort(portName, baudRate, Parity.None);
            serialPort.DataBits = dataBits;
            serialPort.StopBits = StopBits.One;
            serialPort.ReadTimeout = 2000;
            serialPort.WriteBufferSize = 1024;
            serialPort.ReadBufferSize = 1024;
            serialPort.RtsEnable = true;
            serialPort.DtrEnable = true;
            serialPort.ReceivedBytesThreshold = 1;
          
           
            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceivedEventHandler);
        }
        /// <summary>
        /// 串口数据接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void serialPort_DataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
        {
            LogHelper.Debug("shoudao");
            Thread.Sleep(500);
            try
            {
                StringBuilder sb = new StringBuilder();
                bool flag = true;
                while (flag)
                {
                    int len = serialPort.BytesToRead;
                    string receivedata = string.Empty;
                    if (len != 0)
                    {
                        byte[] buff = new byte[len];
                        serialPort.Read(buff, 0, len);
                        receivedata = HexUtils.byteToHexStr(buff);
                        sb.Append(receivedata);
                        
                    }
                    if (len == 0)
                    {
                        flag = false;
                    }
                }
                LogHelper.Debug("receivedata" + sb + "\r\n");

                string hexepc = "";

                //if (sb.ToString().StartsWith("0200") && sb.ToString().EndsWith("03"))//有线读取EPC消息
                if (sb.ToString().StartsWith("0200") )
                {
                    //sb.Clear();
                    //sb.Append ("0200303031303438314632323831313130303030394530303044374534373434314503");

                    if (sb.Length < 60)
                    {
                        sb.Clear();
                        sb.Append ("0200303031303438314632323831313130303030303130303042364634373343353303");
                    }
                    string epcdata = sb.ToString().Substring(12, 48);
                    LogHelper.Debug("epcdata=" + epcdata);
                    hexepc = epcdata;


                    byte[] epcbyte = HexUtils.strToHexByte(epcdata);
                    hexepc = System.Text.Encoding.Default.GetString(epcbyte);
                    TagEpcData tagEpcData = EpcReader.readEpc(epcbyte);

                }
                PSAMHelper = new PSAMHelper();



                bool flag1 = PSAMHelper.verifyUser();
                LogHelper.Debug("flag1" + flag1);
                    
                

                byte[] operator1strbytes = HexUtils.strToHexByte("31323334");
                byte[] operator2strbytes = HexUtils.strToHexByte("31323334");
                string genCloseWriteElsCmd = "";
                //关锁
                //genCloseWriteElsCmd = PSAMHelper.genCloseElsCmd(hexepc, 20000, operator1strbytes, operator2strbytes);
                //CloseWriteEls(genCloseWriteElsCmd.Replace("9000", ""));
                //开锁
                genCloseWriteElsCmd = PSAMHelper.genOpenElsCmd(hexepc, 20000, operator1strbytes, operator2strbytes);
                openWriteEls(genCloseWriteElsCmd.Replace("9000",""));



                
            }
            catch (Exception ex)
            { }
        }
        /// <summary>
        /// 打开端口
        /// </summary>
        public bool Open()
        {
            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    return true;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 发送字节
        /// </summary>
        /// <param name="writeBytes">要发送的字节</param>
        /// <returns></returns>
        public bool Write(byte[] writeBytes)
        {
            if (Open())
            {
                try
                {
                    serialPort.Write(writeBytes, 0, writeBytes.Length);
                    string mergeStr = "发送:";
                    for (int j = 0; j < writeBytes.Length; j++)
                    {
                        mergeStr = mergeStr + writeBytes[j].ToString("x") + " ";
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            return false;
        }
        /// <summary>
        /// 发送字符串
        /// </summary>
        /// <param name="writestrs"></param>
        /// <returns></returns>
        public bool Write(string writeStrs)
        {
            if (Open())
            {
                try
                {
                   
                    byte[] ComBytes = StringAndBytesHelper.strToToHexByte(writeStrs);
                    serialPort.Write(ComBytes, 0, ComBytes.Length);
                    LogHelper.Debug("发送内容" + writeStrs);
                    // serialPort.Write(writeStrs);
                    Thread.Sleep(3000);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }
        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="NumBytes">读取的字节数</param>
        /// <returns></returns>
        public byte[] Read(int NumBytes)
        {
            byte[] inbuffer = null;
            if (serialPort.IsOpen && serialPort.BytesToRead > 0)
            {
                if (NumBytes > serialPort.BytesToRead)
                {
                    NumBytes = serialPort.BytesToRead;
                }
                try
                {
                    inbuffer = new byte[NumBytes];
                    int count = serialPort.Read(inbuffer, 0, NumBytes);
                }
                catch (TimeoutException timeoutEx)
                { }
            }

           
                return inbuffer;
        }
        public byte[] Read()
        {
            StringBuilder sb = new StringBuilder();
            bool flag = true;
            while (flag)
            {
                int len = serialPort.BytesToRead;
                string receivedata = string.Empty;
                if (len != 0)
                {
                    byte[] buff = new byte[len];
                    serialPort.Read(buff, 0, len);
                    receivedata = HexUtils.byteToHexStr(buff);
                    sb.Append(receivedata);

                }
                if (len == 0)
                {
                    break;
                }
            }
            return HexUtils.strToHexByte(sb.ToString());
           // return Read(serialPort.BytesToRead);
        }
        public string ReadLine()
        {
            try
            {
                if (serialPort.IsOpen && serialPort.BytesToRead > 0)
                {
                    string s = serialPort.ReadExisting();
                    return serialPort.ReadLine();
                }
                return null;
            }
            catch (TimeoutException timeoutEx)
            {
                return timeoutEx.Message;
            }
        }
        /// <summary>
        /// 关闭串口
        /// </summary>
        public void Close()
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            { }
        }
        public bool IsOpen
        {
            get
            {
                return serialPort.IsOpen;
            }
        }

        public string  sendAndRs(String hexcmd, long timeout)
        {
            Write(hexcmd);
           
            return null;//超时返回Null
        }
        public string openWriteEls(string OpenWriteElsCmd)
        {
            string cmdstart = "020530303143";
            string lenHexStr = "001C";
            byte[] CloseWriteElsCmdB = Encoding.Default.GetBytes(OpenWriteElsCmd);
            string CloseWriteElsCmdHex = HexUtils.byteToHexStr(CloseWriteElsCmdB);
            string allcmd = lenHexStr + OpenWriteElsCmd;
            byte[] allcmdb = HexUtils.strToHexByte(allcmd);

            string crc=CRCHelper.ToCRC16(allcmdb);
            byte[] crcb = Encoding.Default.GetBytes(crc);
            string crchex = HexUtils.byteToHexStr(crcb);
            string cmddata = cmdstart + CloseWriteElsCmdHex + crchex + "03";
            return sendAndRs(cmddata, 30000);
        }
        public string CloseWriteEls(string CloseWriteElsCmd)
        {
            string cmdstart = "020530303143";
            string lenHexStr = "001C";
            byte[] CloseWriteElsCmdB = Encoding.Default.GetBytes(CloseWriteElsCmd);
            string CloseWriteElsCmdHex = HexUtils.byteToHexStr(CloseWriteElsCmdB);
            string allcmd = lenHexStr + CloseWriteElsCmd;

            byte[] allcmdb = HexUtils.strToHexByte(allcmd);

            string crc = CRCHelper.ToCRC16(allcmdb);
            byte[] crcb = Encoding.Default.GetBytes(crc);
            string crchex = HexUtils.byteToHexStr(crcb);
            string cmddata = cmdstart + CloseWriteElsCmdHex + crchex + "03";
            return sendAndRs(cmddata, 30000);
        }
        public string readEpc()
        {
            return sendAndRs("0204303030343030373303", 5000);
        }


        public bool onlyopLock( string operatorstr, string auditorstr, int num)
        {
            //打开串口并发送指令

            readEpc();
           
            
           
          

            return false;
        }
       
        
    }
}